/*
 * @Author: your name
 * @Date: 2021-07-06 11:38:55
 * @LastEditTime: 2021-07-27 13:50:06
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \Skip\assets\script\Share.ts
 */
// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;
declare const wx;
import Request from "./Request";
import { shareData } from "DataModule";
import { BaseUrl } from "./Data";
import { setStore, getStore } from "./Utils";
@ccclass
export default class Wechat extends cc.Component {

    code: string = '';

    onLoad() {
        // 上线之后再放开
        // if (!this.isWechat()) return;
        // this.initShare({
        //     title: '你的代码我的心',
        //     desc: '爱生活，爱运动，爱自己！走过的路，走过的地方，都是属于我的风景。',
        //     type: 'link',
        //     imgUrl: "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Ff.01ny.cn%2Fforum%2F201210%2F06%2F1020515jrbwmg5zb5mijbr.jpg&refer=http%3A%2F%2Ff.01ny.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1628136197&t=ed20d7e0bcff6c6b4b4fda271a74c33c",
        //     dataUrl: ''
        // });
        // let code = this.getQueryString("code")
        // let userinfo = getStore('userinfo', true)
        // if (userinfo) return;
        // if (code && code !== this.code) {
        //     this.code = code
        //     this.wxLogin();
        // } else {
        //     this.wxAuthorize();
        // }
    }
    // 1、提取微信返回的url的code和state   // ③
    getQueryString(name: string) {
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        let r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }
    /**
     * 初始化分享
     * @param share 
     */
    initShare(share: shareData) {
        this.initJssdk(share);
    }
    // 微信授权
    wxAuthorize() {
        let uri = this.getUri();
        let appid = "wxeaec62232b604b70";
        const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect`
        window.location.href = url
    }
    // 微信登录
    wxLogin() {
        let uri = this.getUri();
        Request.inst.httpGet(`${BaseUrl}/wx/wxUser/login?code=${this.code}&url=${uri}`, (data) => {
            console.log(data)
            let test = cc.find('Canvas/test').getComponent(cc.Label)
            test.string = data.nickName || '获取用户成功';
            setStore('userinfo', data, true)
            // 本地缓存
        })

    }
    // 获取当前网页的地址并进行编码
    getUri(): string {
        return encodeURIComponent(window.location.href.split('#')[0]);
    }

    //判断是否在微信中    
    isWechat() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/micromessenger/i).toString() == 'micromessenger') {
            return true;
        } else {
            return false;
        }
    }



    initJssdk(share: shareData, callback: Function = () => { }) {
        var uri = window.location.href.split('#')[0];
        console.log("uri", uri)

        // 发起请求
        Request.inst.httpGet(`${BaseUrl}/wx/share/getWxInfo?url=${uri}`, (data) => {
            let result = data.data
            wx.config({
                debug: false,
                appId: "wxeaec62232b604b70",
                timestamp: result.timestamp,
                nonceStr: result.noncestr,
                signature: result.signature,
                jsApiList: [ //这里是需要用到的接口名称  
                    'checkJsApi', //判断当前客户端版本是否支持指定JS接口  
                    'updateTimelineShareData', //分享接口  
                    'getLocation', //获取位置  
                    'openLocation', //打开位置  
                    'scanQRCode', //扫一扫接口  
                    'chooseWXPay', //微信支付  
                    'chooseImage', //拍照或从手机相册中选图接口  
                    'previewImage', //预览图片接口  
                    'uploadImage', //上传图片 
                    'updateAppMessageShareData',
                    'onMenuShareQQ'
                ]
            });
            wx.ready(() => {
                wx.updateTimelineShareData({
                    title: share.title, // 分享标题
                    link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: share.imgUrl, // 分享图标
                    success: function () {
                        // 用户点击了分享后执行的回调函数
                        if (callback) {
                            // callback(res.data);
                        }
                    }
                });
                wx.updateAppMessageShareData({
                    title: share.title, // 分享标题
                    desc: share.desc, // 分享描述
                    link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: share.imgUrl, // 分享图标
                    type: share.type, // 分享类型,music、video或link，不填默认为link
                    dataUrl: share.dataUrl, // 如果type是music或video，则要提供数据链接，默认为空
                    success: function () {
                        // 用户点击了分享后执行的回调函数
                        if (callback) {
                            // callback(res.data);
                        }
                    }
                });
                wx.onMenuShareQQ({
                    title: share.title, // 分享标题
                    desc: share.desc, // 分享描述
                    link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: share.imgUrl, // 分享图标
                    success: function () {
                        // 用户点击了分享后执行的回调函数
                        if (callback) {

                        }
                    }
                });
                wx.onMenuShareQZone({
                    title: share.title, // 分享标题
                    desc: share.desc, // 分享描述
                    link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: share.imgUrl, // 分享图标
                    success: function () {
                        // 用户点击了分享后执行的回调函数
                        if (callback) {

                        }
                    }
                });
            })
        })
    }
    // 保存照片到本地
    saveImage() {

    }


    // update (dt) {}
}
